package com.qfedu.interceptor;

import com.qfedu.entity.Admin;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author:huayuzhuo
 * @email:2798866329@qq.com
 * @desc: 拦截登录请求
 * @datatime: 2022/10/29 17:53
 */
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从这里拿取请求信息
        Admin adminLogin = (Admin) request.getSession().getAttribute("adminLogin");

        if (adminLogin == null){
            String header = request.getHeader("X-Requested-With");
            //证明是阿贾克斯请求
            if (header != null && header.equals("XMLHttpRequest")){
                response.getWriter().write("{'code':0,'info':'未登录'}");
            } else {
                //否则就是非阿贾克斯请求,重定向到登录
                response.sendRedirect(request.getContextPath() + "/login.html");
            }
            return false;
        } else {
            return true;
        }


    }



}
